package com.orgcent.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

/**
 * 当用户点击退出的时候处理上传的事情,但是程序又不能完全退出,并且要求界面马上切换回HOME 桌面状态.
 * 方法：将Activity隐藏.显示桌面.等操作完成后在完全退出程序.
 */
public class HideActivityShowHome extends Activity {
	private static final String TAG = HideActivityShowHome.class
			.getSimpleName();

	private Context context = HideActivityShowHome.this;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Button btn = new Button(this);
		btn.setText("上传数据，退出系统");
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				createExitDialog();
			}
		});
		
		setContentView(btn);
	}

	private void createExitDialog() {
		AlertDialog dialog = new AlertDialog.Builder(context)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						showHOME(); //显示桌面

						Log.i(TAG, "hide activity --- show home. time : " + System.currentTimeMillis());
						new Thread(new Runnable() {

							@Override
							public void run() {
								SystemClock.sleep(5000);
								Log.i(TAG, "finish activity. time : " + System.currentTimeMillis());
								HideActivityShowHome.this.finish();
							}
						}).start();
					}
				}).setNegativeButton("取消", null).setMessage("确定要退出吗?")
				.setTitle("提示").create();
		dialog.show();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.i(TAG, "destory activity. time : " + System.currentTimeMillis());
		System.exit(0);
	}

	// 隐藏activity到后台,打开HOME Launcher
	private void showHOME() {
		PackageManager pm = getPackageManager();
		ResolveInfo homeInfo = pm.resolveActivity(
				new Intent(Intent.ACTION_MAIN)
						.addCategory(Intent.CATEGORY_HOME), 0);
		ActivityInfo ai = homeInfo.activityInfo;
		Intent startIntent = new Intent(Intent.ACTION_MAIN);
		startIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		startIntent.setComponent(new ComponentName(ai.packageName, ai.name));
		startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(startIntent);
	}
}
